import React, { Component } from "react";
import { Upload, Modal, message } from "antd";
import { PlusOutlined } from "@ant-design/icons";

// function getBase64(file) {
//   return new Promise((resolve, reject) => {
//     const reader = new FileReader();
//     reader.readAsDataURL(file);
//     reader.onload = () => resolve(reader.result);
//     reader.onerror = (error) => reject(error);
//   });
// }
//用于图片上传
export default class PicturesWall extends Component {
  state = {
    previewVisible: false,
    previewImage: "",
    previewTitle: "",
    fileList: [
      //   {
      //     uid: "-1",
      //     name: "image.png",
      //     status: "done",
      //     url: "https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png",
      //   },
    ],
  };

  getImgs = () => {
    return this.state.fileList.map((file) => file.name);
  };
  handleCancel = () => this.setState({ previewVisible: false });

  handlePreview = async (file) => {
    // if (!file.url && !file.preview) {
    //   file.preview = await getBase64(file.originFileObj);
    // }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
      previewTitle:
        file.name || file.url.substring(file.url.lastIndexOf("/") + 1),
    });
  };

  handleChange = ({ file, fileList }) => {
    if (file.status === "done") {
      const result = file.response;
      //一旦上传成功，将当前上传的file信息修正
      if (result.status === 0) {
        message.success("上传图片成功");
        const { name, url } = result.data;
        const file2 = fileList[fileList.length - 1];
        file2.name = name;
        file2.url = url;
      } else {
        message.error("上传图片失败");
      }
      this.setState({ fileList });
    }
  };
  render() {
    const { previewVisible, previewImage, fileList, previewTitle } = this.state;
    const uploadButton = (
      <div>
        <PlusOutlined />
        <div style={{ marginTop: 8 }}>Upload</div>
      </div>
    );
    return (
      <>
        <Upload
          action="/manage/img/upload"
          accept="image/*" //只接受图片类型
          listType="picture-card"
          name="image" //请求参数名
          fileList={fileList}
          onPreview={this.handlePreview}
          onChange={this.handleChange}
        >
          {fileList.length >= 8 ? null : uploadButton}
        </Upload>
        <Modal
          visible={previewVisible}
          title={previewTitle}
          footer={null}
          onCancel={this.handleCancel}
        >
          <img alt="example" style={{ width: "60%" }} src={previewImage} />
        </Modal>
      </>
    );
  }
}
